package com.shop.controller;

import com.shop.vo.PermVo;
import com.shop.annotation.RequiresPermissionsDesc;
import com.shop.pojo.DtsRole;
import com.shop.service.DtsPermissionService;
import com.shop.service.DtsRoleService;
import com.shop.util.Permission;
import com.shop.util.PermissionUtil;
import com.shop.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName AdminRoleController
 * @Author xiao宋
 * @Date 16:02  2022/10/14
 * @Version 1.0
 * @Description 包含了关于角色的各种操作
 */
@Slf4j
@RestController
@RequestMapping("/admin/role")
public class AdminRoleController {
    @Autowired
    DtsRoleService roleService;
    @Autowired
    DtsPermissionService permissionService;
    @Autowired
    ApplicationContext context;

    /**
     * 角色授权
     *
     * @param roleId
     * @return
     */
    @GetMapping("/permissions")
    public Object permissions(Integer roleId) {
        log.debug("开始执行角色授权。AdminRoleController--> permissions 方法");
//        扫描目录下的权限
            List<Permission> list = PermissionUtil.listPermission(context, "com.shop.controller");
        log.debug("扫描包扫描到的数据list为{}", list);
        List<PermVo> systemPermissions = PermissionUtil.listPermVo(list);
//        判断是不是超级管理员
        boolean flag = roleService.isSuperAdmin(roleId);
        Set<String> assignedPermissions = null;
        if (flag) {
            assignedPermissions = PermissionUtil.listPermissionString(list);
        } else {
            assignedPermissions = permissionService.findPermsById(new Integer[]{roleId});
        }
//      用 map 封装数据
        Map<String, Object> data = new HashMap<>();
        data.put("systemPermissions", systemPermissions);
        data.put("assignedPermissions", assignedPermissions);
        log.debug("角色授权成功。AdminRoleController--> permissions 方法");
        return ResponseUtil.ok(data);
    }

    /**
     * 修改权限
     * <p>前端会传一个json数组，如果是超级管理员就啥都不管直接返回
     */

    @PostMapping("/permissions")
    public Object updatePermissions(@RequestBody Map<String, Object> map) {
        int roleId = Integer.parseInt(String.valueOf(map.get("roleId")));
        List<String> permissions = (List<String>) map.get("permissions");

        if (roleService.isSuperAdmin(roleId)) {
            return ResponseUtil.ok();
//            permissions=new ArrayList<>();
//            permissions.add("*");
        }
        permissionService.updatePermissions(roleId, permissions);

        return ResponseUtil.ok();
    }

    /**
     * 删除角色
     *
     * @param role
     * @return
     */
    @RequiresPermissions("admin:role:delete")
    @RequiresPermissionsDesc(menu = {"系统管理", "角色管理"}, button = "角色删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody DtsRole role) {
        log.debug("执行角色删除。AdminRoleController--> delete 方法");
        try {
            roleService.delete(role);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1, e.getMessage());
        }
        log.debug("角色逻辑删除成功。AdminRoleController--> delete 方法");
        return ResponseUtil.ok();
    }
    @RequiresPermissions("admin:role:update")
    @RequiresPermissionsDesc(menu = { "系统管理", "角色管理" }, button = "角色编辑")
    @PostMapping("/update")
    public Object update(@RequestBody DtsRole role) {
        log.debug("开始执行编辑角色权限");
        roleService.update(role);
        return ResponseUtil.ok(role);
    }

    /**
     * 添加角色
     *
     * @param role
     * @return
     */
    @RequiresPermissions("admin:role:creat")
    @RequiresPermissionsDesc(menu = {"系统管理", "角色管理"}, button = "角色添加")
    @PostMapping("/create")
    public Object creat(@RequestBody DtsRole role) {
        log.debug("开始执行添加角色");
        log.debug("从前端拿的要添加的角色名：{}，角色说明：{}",role.getName(),role.getDesc());
        roleService.insert(role);
        return ResponseUtil.ok(role);
    }

    /**
     * 显示角色列表
     *
     * @param page     第几页
     * @param limit    每页条数
     * @param sort     按此字段排序
     * @param order    正 <-> 倒  排序
     * @param rolename
     * @return
     */
    @RequiresPermissions("admin:role:list")
    @RequiresPermissionsDesc(menu = {"系统管理", "角色管理"}, button = "角色查询")
    @GetMapping("/list")
    public Object list(
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
            @RequestParam(value = "limit", required = false, defaultValue = "20") Integer limit,
            @RequestParam(value = "sort", required = false, defaultValue = "add_time") String sort,
            @RequestParam(value = "order", required = false, defaultValue = "desc") String order,
            String rolename
    ) {
        Map<String, Object> data = roleService.findByPage(page, limit, sort, order, rolename);
        return ResponseUtil.ok(data);
    }

    @RequestMapping("/options")
    public Object option() {
        List<DtsRole> roleList = roleService.findAll();

        List<Map<String, Object>> data = roleList.stream().map(role -> {
            Map<String, Object> map = new HashMap<>();
            map.put("label", role.getName());
            map.put("value", role.getId());
            return map;
        }).collect(Collectors.toList());
        return ResponseUtil.ok(data);
    }

}
